package com.sgmw.iamgeqr_flutter_plugin

import android.content.Intent
import android.os.Bundle
import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import java.net.URI
import android.net.Uri
import android.database.Cursor
import android.provider.MediaStore

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;

class ImageActivity : Activity() {

    private var REQUEST_CODE : Int = 100

    /*override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
    }*/

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val intent = Intent()
        intent.type = "image/*" // 设置只选择图片类型
        intent.action = Intent.ACTION_GET_CONTENT // 设置动作
        startActivityForResult(intent, REQUEST_CODE) // 启动 Activity 并等待结果
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            val imageUri = data.data
            if (imageUri != null) {
                val imagePath = getRealPathFromUri(imageUri) // 获取图片路径
                //解析
                if (imagePath != null) {
                    barcodeImage(imagePath)
                }else{
                    sendFlutter("error");
                }
            }else{
                sendFlutter("error");
            }
        }else{
            sendFlutter("error");
        }
    }

    fun getRealPathFromUri(uri: Uri): String? {
        var cursor: Cursor? = null
        var path: String? = null
        try {
            val proj = arrayOf(MediaStore.Images.Media.DATA)
            cursor = contentResolver.query(uri, proj, null, null, null)
            if (cursor != null && cursor.moveToFirst()) {
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                path = cursor.getString(columnIndex)
            }
        } finally {
            cursor?.close()
        }
        return path
    }

    fun barcodeImage(image:String){
        val imagePath = image // 替换为你的图片路径
        val bitmap = BitmapFactory.decodeFile(imagePath)
        val result = decodeQRCode(bitmap) // 解析二维码
        if (result != null) {
            // 解析成功，处理结果
            sendFlutter(result);
        } else {
            // 解析失败
            sendFlutter("error");
        }
    }

    fun decodeQRCode(bitmap: Bitmap): String? {
        return try {
            val width = bitmap.width
            val height = bitmap.height
            val pixels = IntArray(width * height)
            bitmap.getPixels(pixels, 0, width, 0, 0, width, height)

            val source = RGBLuminanceSource(width, height, pixels)
            val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
            val reader = MultiFormatReader()
            val result = reader.decode(binaryBitmap)
            result.text
        } catch (e: NotFoundException) {
            e.printStackTrace()
            null
        }
    }

    fun sendFlutter(data : String?){
        var intent = Intent("com.sgmw.flutter.imageQr");
        intent.putExtra("QRTEXT", data);
        sendBroadcast(intent)
        finish()
    }
}